using HarmonyLib;
using System.Collections;
using UnityEngine;
using ItemStatsSystem.Items;
using Duckov.Utilities;

namespace AllGunsSixSlots
{
    // 物品初始化补丁 - 处理从存档加载的枪械
    [HarmonyPatch(typeof(ItemStatsSystem.Item), "Initialize")]
    public class AllGunsItemInitializePatch
    {
        [HarmonyPostfix]
        public static void Postfix(ItemStatsSystem.Item __instance)
        {
            try
            {
                var gunSetting = __instance.GetComponent<ItemSetting_Gun>();
                if (gunSetting == null) return;
                
                // 启动异步处理
                gunSetting.StartCoroutine(HandleItemInitializeAsync(__instance, gunSetting));
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError($"[AllGunsSixSlots] Item.Initialize补丁执行失败: {ex.Message}\n{ex.StackTrace}");
            }
        }

        private static IEnumerator HandleItemInitializeAsync(ItemStatsSystem.Item item, ItemSetting_Gun gunSetting)
        {
            // 等待一帧，确保Initialize完全完成
            yield return null;

            // 检查插槽数量
            if (item.Slots == null)
            {
                UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] 物品插槽集合为null，无法处理");
                yield break;
            }

            string gunName = item.DisplayName ?? "未知枪械";

            // 如果已经是6个插槽，说明已经修复过了，跳过
            if (item.Slots.Count == 6)
            {
                UnityEngine.Debug.Log($"[AllGunsSixSlots] {gunName} 已有6个插槽，跳过修复");
                yield break;
            }
            UnityEngine.Debug.Log($"[AllGunsSixSlots] 检测到从存档加载的枪械 {gunName}，开始异步修复插槽: {item.Slots.Count} → 6");

            // 等待系统资源就绪
            yield return WaitForItemSystemsReady();

            // 异步执行插槽修复
            yield return AllGunsSettingPatch.ModifyAllGunsSlotsAsync(item, gunName);

            UnityEngine.Debug.Log($"[AllGunsSixSlots] 完成异步修复枪械 {gunName} 的插槽");
        }

        private static IEnumerator WaitForItemSystemsReady()
        {
            // 等待必要的系统资源加载完成
            int maxWaitFrames = 15; // 增加等待帧数，存档加载可能更慢
            int currentFrame = 0;

            while (currentFrame < maxWaitFrames)
            {
                // 检查Tag系统是否就绪
                var allTags = Resources.FindObjectsOfTypeAll<Tag>();
                if (allTags != null && allTags.Length > 10) // 假设有足够多的Tag加载
                {
                    // 额外等待一帧确保完全稳定
                    yield return null;
                    break;
                }

                currentFrame++;
                yield return null;
            }

            if (currentFrame >= maxWaitFrames)
            {
                UnityEngine.Debug.LogWarning($"[AllGunsSixSlots] 物品初始化等待系统就绪超时，继续执行...");
            }
        }
    }
}